package com.lvcoding.miaoshademo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvcoding.miaoshademo.domain.User;
import com.lvcoding.miaoshademo.mapper.UserMapper;
import com.lvcoding.miaoshademo.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int saveUserCount(Integer userId) {
        // 根据不同用户id生成调用次数的key
        String limitKey = "LIMIT_" + userId;
        // 获取key的调用次数
        String limitNum = this.stringRedisTemplate.opsForValue().get(limitKey);
        int limit = -1;
        if(limitNum == null) {
            // 第一次调用放入redis中设置为0
            this.stringRedisTemplate.opsForValue().set(limitKey, "0", 3600, TimeUnit.SECONDS);
        } else {
            // 不是第一次调用每次+1
            limit = Integer.parseInt(limitNum) + 1;
            this.stringRedisTemplate.opsForValue().set(limitKey, String.valueOf(limit), 3600, TimeUnit.SECONDS);
        }

        return limit;
    }

    @Override
    public boolean getUserCount(Integer userId) {
        // 根据不同用户id生成调用次数的key
        String limitKey = "LIMIT_" + userId;
        // 获取key的调用次数
        String limitNum = this.stringRedisTemplate.opsForValue().get(limitKey);
        if(limitNum == null) {
            // 为空直接抛弃，说明key出现异常
            log.error("该用户没有申请【访问验证值】，疑似异常");
            return true;
        }
        // 单位时间请求的阀值
        int yuzhi = 10;

        return Integer.parseInt(limitNum) > yuzhi; // false表示没有超过 true代表超过
    }
}
